package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.ToastUtils;
import com.stark.nettool.lib.NetToolBox;
import com.stark.nettool.lib.TraceRouteInfo;
import com.stark.nettool.lib.TraceRouter;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityTraceBinding;

public class TraceActivity extends BaseAc<ActivityTraceBinding> {

    private String url;
    private int num = 4;
    private boolean isQuery = false;

    @Override
    protected int onCreate() {
        return R.layout.activity_trace;
    }

    @Override
    protected void initView() {
        mDataBinding.ivTraceBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.tvQuery.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvQuery://开始
                if (isQuery) return;
                url = mDataBinding.etUrl.getText().toString();
                if (TextUtils.isEmpty(url)) {
                    mDataBinding.etUrl.requestFocus();
                    ToastUtils.showShort(getString(R.string.please_input_domain_ip));
                    return;
                }
                isQuery = true;
                startTcp();
                break;
        }
    }

    @Override
    protected void initData() {

    }

    private void startTcp() {
        showDialog(getString(R.string.loading));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                int count = 4;
                StringBuilder builder = new StringBuilder();
                String line = null;
                try {
                    Process pro = Runtime.getRuntime().exec("ping " + url);
                    BufferedReader buf = new BufferedReader(new InputStreamReader(
                            pro.getInputStream()));
                    buf.readLine();
                    for (int i = 0; i < count; i++) {
                        line = buf.readLine();
                        builder.append(line + "\n");
                    }
                    buf.close();
                    mDataBinding.tvResult.setText(builder.toString());
                    mDataBinding.llResult.setVisibility(View.VISIBLE);
                    isQuery = false;
                    dismissDialog();
                } catch (Exception ex) {
                    dismissDialog();
                }
            }
        },100);
    }

}